const express = require("express");
const router = express.Router();

const fs = require("fs");

// 该文件里的接口都是二级路由

// 随机数据
function randomStr(num) {
  var str = "";
  var dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-";
  for (var i = 0; i < num; i++) {
    var index = Math.floor(Math.random() * dict.length);
    str += dict[index];
  }
  return str;
}

// 操作文件的路径
const tablePath = "./interface/tables/table.txt";

// 读取文件
const readFile = () => {
  try {
    const data = fs.readFileSync(tablePath, "utf-8");
    return data;
  } catch (error) {
    return "读取失败";
  }
};

/*
 * data:  不包含list的纯数据数组[]
 * 返回值: success || error
 */
// 写入文件
function writeFile(data) {
  const writeContent = JSON.stringify({ list: data });
  try {
    fs.writeFileSync(tablePath, writeContent);
    return "success";
  } catch (error) {
    return "error";
  }
}

// 初始化数据
const table = [];
function getTable() {
  for (let i = 0; i < 174; i++) {
    table.push({
      id: i,
      name: randomStr(5),
      sex: (i % 2 == 0) | (i % 3 == 0) ? "man" : "woman",
      zipCode: 0,
      address: randomStr(20),
    });
  }
}

/*
 * 增加数据接口
 */
router.post("/add", function (request, response) {
  var data = "";
  request.on("data", (chunk) => {
    data += chunk;

    const parseData = JSON.parse(readFile());
    var newData = parseData.list;
    var res = {
      code: 471,
      msg: "添加失败",
    };
    const id = newData[newData.length - 1].id + 1;

    newData.push({
      ...JSON.parse(data),
      id,
    });
    if (writeFile(newData) == "success")
      res = {
        code: 200,
        msg: "添加成功",
      };
    response.send(res);
  });
});

// 删除接口 done
router.get("/delete", function (request, response) {
  const { id } = request.query;
  const parseData = JSON.parse(readFile());
  // 筛选满足条件数据
  const filterTable = parseData.list.filter((item) => item.id != id);
  let res = {
    code: 472,
    msg: "删除失败",
  };
  if (writeFile(filterTable) == "success") {
    res = {
      code: 200,
      msg: "删除成功",
    };
  }
  response.send(res);
});

// 编辑接口 done
router.post("/modify", function (request, response) {
  var data = "";
  request.on("data", (chunk) => {
    data += chunk;

    // 读取文件数据并序列化
    const parseData = JSON.parse(readFile());
    let list = parseData.list;
    const parseParams = JSON.parse(data);

    const newData = list.map((item) => {
      if (item.id == parseParams.id) {
        item = {
          ...parseParams,
        };
      }
      return item;
    });
    let res = {
      code: 473,
      msg: "修改失败",
    };
    if (writeFile(newData) == "success") res = { code: 200, msg: "修改成功" };
    response.send(res);
  });
});

// 获取list数据 done
/*
 * page:页码  默认为1
 * pageSize:一页数据长度 默认为10
 */
router.get("/list", function (request, response) {
  // getTable();
  // writeFile(table);
  // response.send({
  //   data: [],
  // });

  var res = {
    code: 470,
    data: null,
  };
  // 读取文件数据并序列化
  const parseData = JSON.parse(readFile());
  // 设置默认值
  const { page = 1, pageSize = 10 } = request.query;
  const start = (page * 1 - 1) * (pageSize * 1);
  const end = page * 1 * (pageSize * 1);

  // 截取对应数据返回
  const data = parseData.list ? parseData.list.slice(start, end) : [];
  if (parseData.list) {
    res = {
      code: 200,
      data: {
        total: parseData.list.length,
        page: page * 1,
        pageSize: pageSize * 1,
        data,
      },
    };
  }
  response.send(res);
});

// 获取某条数据 done
router.get("/info", function (request, response) {
  // 读取文件数据并序列化
  const parseData = JSON.parse(readFile());
  // 设置默认值
  const { id } = request.query;
  // 截取对应数据返回
  const data = parseData.list.filter((item) => item.id == id) || [];
  response.send({
    code: 200,
    data,
  });
});

module.exports = router;
